package com.example.cylooq.niceview.network


import android.content.Context
import android.util.Log
import java.io.File
import okhttp3.Cache
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.Retrofit
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit

/**
 * Created by RuiChang on 2017/08/24.
 * Kotlin构建函数需要传入参数必须要有constructor，如果不传入参数，可以省略
 * Retrofit和OKHttp库需要学习
 */
class RetrofitClient private constructor(context: Context, baseUrl: String) {
    val DEFAULT_TIMEOUT: Long = 20
    var httpCacheDirectory: File? = null
    var cache: Cache? = null
    var okHttpClient: OkHttpClient? = null
    var mContext: Context = context
    var url = baseUrl
    var retrofit: Retrofit? = null

    init {
        //缓存地址
        if (httpCacheDirectory == null) {
            httpCacheDirectory = File(mContext.cacheDir, "video")
        }

        try {
            if (cache == null) {
                cache = Cache(httpCacheDirectory, 10 * 1024 * 1024)
            }
        } catch (e: Exception) {
            Log.e("RetrofitClient Okhttp", "Can not create http cache", e)
        }
        okHttpClient = OkHttpClient.Builder()
                .addNetworkInterceptor(
                        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .cache(cache)
                .addInterceptor(CacheInterceptor(context))
                .addNetworkInterceptor(CacheInterceptor(context))
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .build()
        retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url)
                .build()
    }

    companion object {
         @Volatile
        var instance:RetrofitClient?=null
        fun getInstance(context:Context,baseUrl: String):RetrofitClient{
            if(instance==null){
            /*
            在Java中，synchronized关键字是用来控制线程同步的，就是在多线程的环境下，控制synchronized
            代码段不被多个线程同时执行。synchronized既可以加在一段代码上，也可以加在方法上。8?
             */
                synchronized(RetrofitClient::class){
                    if(instance==null){
                        instance= RetrofitClient(context,baseUrl)
                    }
                }
            }
            return instance!!
        }
    }
    fun <T> create(service: Class<T>?): T? {
        if (service == null) {
            throw RuntimeException("Api service is null!")
        }
        return retrofit?.create(service)
    }



}